/*
 * Copyright (c) 1995 - 2008 Sun Microsystems, Inc.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Sun Microsystems nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */ 

package LayoutBluetooth;

import javax.swing.AbstractButton;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.ImageIcon;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

import net.sf.bluecove.Configuration;
import net.sf.bluecove.Switcher;
import net.sf.bluecove.se.BlueCoveSpecific;
import net.sf.bluecove.se.FileStorage;
import net.sf.bluecove.se.JavaSECommon;

import org.bluecove.tester.log.Logger;

import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.WindowEvent;

/* 
 * ButtonDemo.java requires the following files:
 *   images/right.gif
 *   images/middle.gif
 *   images/left.gif
 */
public class basicComponets extends JPanel
                        implements ActionListener {
	public void windowClosing(WindowEvent w) {
            				quit();}
	
    protected JButton initialConnection, stopConnection;
    protected JTextField textField;
    protected JTextArea textArea;
    private final static String newline = "\n";

    public void LayoutInitiate() {


    	//end generated code
    	
        JPanel connectionStart = new JPanel();
        
        connectionStart.setLayout(new FlowLayout());
        connectionStart.setSize(300, 650);
        connectionStart.setVisible(true);
        connectionStart.setBounds(500, 500, 10, 10);
        
        //ImageIcon leftButtonIcon = createImageIcon("mobile.gif");
        //ImageIcon middleButtonIcon = createImageIcon("images/middle.gif");
        //ImageIcon rightButtonIcon = createImageIcon("images/left.gif");

        initialConnection = new JButton("Start Connection");
/*      initialConnection.setVerticalTextPosition(AbstractButton.CENTER);
        initialConnection.setHorizontalTextPosition(AbstractButton.LEFT); //aka LEFT, for left-to-right locales
        initialConnection.setAlignmentX(LEFT_ALIGNMENT);*/
        initialConnection.setBounds(100, 100, 100, 10);
        initialConnection.setMnemonic(KeyEvent.VK_D);
        initialConnection.setActionCommand("start");
        
        
        stopConnection = new JButton("Stop Connection");
        //stopConnection.setVerticalTextPosition(AbstractButton.CENTER);
        //stopConnection.setHorizontalTextPosition(AbstractButton.LEFT);
        stopConnection.setMnemonic(KeyEvent.VK_M);
        stopConnection.setBounds(100, 200, 100, 10);
        //stopConnection.setLayout(getLayout());
        //Initials Connection
        stopConnection.setActionCommand("stop");
        stopConnection.setEnabled(false);
        

        initialConnection.addActionListener(this);
        stopConnection.addActionListener(this);

        initialConnection.setToolTipText("Click this button to disable the middle button.");
        stopConnection.setToolTipText("This middle button does nothing when you click it.");
        
        //b3 = new JButton("Stop Connection", rightButtonIcon);
        //Use the default text position of CENTER, TRAILING (RIGHT).
        //b3.setMnemonic(KeyEvent.VK_E);
        //b3.setEnabled(false);

        //Listen for actions on buttons 1 and 3.
        

        

        textField = new JTextField(2);
        textField.addActionListener(this);
        
        textArea = new JTextArea(5, 20);
        textArea.setEditable(false);
        JScrollPane scrollPane = new JScrollPane(textArea);

        //Add Components to this panel.
        GridBagConstraints c = new GridBagConstraints();
        c.gridwidth = GridBagConstraints.REMAINDER;
        c.fill = GridBagConstraints.HORIZONTAL;
        c.fill = GridBagConstraints.BOTH;
        c.weightx = 1.0;
        c.weighty = 1.0;
        
        //add Buttons to first Panel
        connectionStart.add(initialConnection);
        connectionStart.add(stopConnection);        
        connectionStart.add(textArea);
        connectionStart.add(textField);
        
        //Add Components to this container, using the default FlowLayout.
        add(connectionStart);
        
        //the following is added in the panel above now
/*      add(initialConnection);
        add(stopConnection);
        add(scrollPane, c);
        add(textField, c);*/
    }

    public void actionPerformed(ActionEvent e) {
        if ("start".equals(e.getActionCommand())) {
			try {
				Switcher.startClient();
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}        	
        	stopConnection.setEnabled(true);
            initialConnection.setEnabled(false);
        } else if ("stop".equals(e.getActionCommand())) {
			try {
				Switcher.clientShutdown();
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
        	stopConnection.setEnabled(false);
            initialConnection.setEnabled(true);
        }		
        //if ("append".equals(e.getActionCommand())){
        String text = textField.getText();
        textArea.append(text + newline);
        textField.selectAll();
        textArea.setCaretPosition(textArea.getDocument().getLength());
        //}

        //Make sure the new text is visible, even if there
        //was a selection in the text area.
    }

    /** Returns an ImageIcon, or null if the path was invalid. */
    protected static ImageIcon createImageIcon(String path) {
        java.net.URL imgURL = basicComponets.class.getResource(path);
        if (imgURL != null) {
            return new ImageIcon(imgURL);
        } else {
            System.err.println("Couldn't find file: " + path);
            return null;
        }
    }

    /**
     * Create the GUI and show it.  For thread safety, 
     * this method should be invoked from the 
     * event-dispatching thread.
     */
    
    
    private static void createAndShowGUI() {

        //Create and set up the window.
        JFrame frame = new JFrame("Blueswing Software");
        
        //Create and set up the content pane.
        basicComponets newContentPane = new basicComponets();
        newContentPane.setOpaque(true); //content panes must be opaque
        frame.setContentPane(newContentPane);
        frame.setLayout(new FlowLayout ());
        //Set the Size
        //frame.setLocationRelativeTo(null);
        //frame.setLayout(null);
        //Display the window in the tightest format possible.
        //frame.pack();
        //Sets the frame in a centered location;
        frame.setLocationByPlatform(true);
        
        //Sets the size of the window
        frame.setSize(1000, 300); 
        frame.setVisible(true);

    }

    public static void main(String[] args) {
		Logger.debug("Stated app");
		Logger.debug("OS:" + System.getProperty("os.name") + "|" + System.getProperty("os.version") + "|"
				+ System.getProperty("os.arch"));
		Logger.debug("Java:" + System.getProperty("java.vendor") + " " + System.getProperty("java.version") + " " +System.getProperty("java.vm.version"));
    	//Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.
        
		try {
			JavaSECommon.initOnce();
			Configuration.storage = new FileStorage();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI(); 
            }
        });
    }
    
    
	private void quit() {
		Logger.debug("quit");
		Switcher.clientShutdown();
		Switcher.serverShutdownOnExit();

		Rectangle b = this.getBounds();
		Configuration.storeData("main.x", String.valueOf(b.x));
		Configuration.storeData("main.y", String.valueOf(b.y));
		Configuration.storeData("main.height", String.valueOf(b.height));
		Configuration.storeData("main.width", String.valueOf(b.width));

		//Logger.removeAppender(this);
		BlueCoveSpecific.removeAppender();

		// this.dispose();
		System.exit(0);
	}
	
	
}
